package com.yin.myproject.thread.spinlock;

import java.util.concurrent.atomic.AtomicBoolean;

/**
 * 回退算法，降低锁争用的几率 
 * @author Eason
 * @create 2018-02-09 11:04
 **/
public class BackoffLock implements Lock{
    private final int MIN_DELAY, MAX_DELAY;

    private AtomicBoolean mutex = new AtomicBoolean(false);

    public BackoffLock(int min, int max){
        MIN_DELAY = min;
        MAX_DELAY = max;
    }

    @Override
    public void lock() {
        //增加回退对象
        Backoff backoff = new Backoff(MIN_DELAY, MAX_DELAY);
        while (true){
            while (mutex.get()){

            }
            if(!mutex.getAndSet(true)){
                return;
            }else {
                try {
                    backoff.backOff();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }
    }

    @Override
    public void unlock() {
        mutex.set(false);
    }

    @Override
    public String toString(){
        return "TTASLock";
    }
}
